package opt_io

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
)

func isCheck(e error) {
	if e != nil {
		log.Fatalln("opt file is err", e)
	}
}

func file_io() {
	// 读取文件
	file, err := os.ReadFile("./opt_io_test.go")
	isCheck(err)
	fmt.Println("file Content is ", string(file))

	open, err := os.Open("./opt_io_test.go")
	isCheck(err)
	fileByte := make([]byte, 1024)
	lineNum, err := open.Read(fileByte)
	isCheck(err)

	fmt.Printf("count line number %d  bytes: %s\n", lineNum,
		string(fileByte[:lineNum]))

	// 指定偏移量读取
	ret, err := open.Seek(6, 0)
	isCheck(err)
	b2 := make([]byte, 2)
	n2, err := open.Read(b2)
	isCheck(err)
	fmt.Printf("%d bytes @ %d: ", n2, ret)
	fmt.Printf("%v\n", string(b2[:n2]))

	r4 := bufio.NewReader(open)
	b4, err := r4.Peek(5)
	isCheck(err)
	fmt.Printf("5 bytes: %s\n", string(b4))

	fmt.Println("============write===========")

	for i := 0; i < 1000; i++ {
		write_content := []byte(fmt.Sprintf("hello world %d\n", i))
		//FileMode 代表文件的模式和权限位
		os.WriteFile("./write.out", write_content, 0644)
	}
}

func read_file() {
	open, err := os.Open("./opt_io.go")
	isCheck(err)
	defer open.Close()
	reader := bufio.NewReader(open)

	for {
		readString, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		fmt.Println(readString)
	}

	// 一次性读取，适合小文件
	file, err := os.ReadFile(".opt_io.go")
	isCheck(err)
	fmt.Printf("%s\n", file)
}

type address struct {
	addressStr string
}
type person struct {
	name       string
	age        int
	addressArr []address
}

func struct_tobuffer() {
	// nil 空指针
	var personprt *person
	var person1 person
	// new 默认构造
	var personprt2 = new(person)

	var personprt3 = &person{}

	fmt.Println(personprt, "=====",
		person1, "====", personprt2, "=====", personprt3)

}
